package ch.fusun.baron.basic.turntask;

import ch.fusun.baron.core.injection.Configure;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.player.Dynasty;
import ch.fusun.baron.player.Gender;
import ch.fusun.baron.player.Player;
import ch.fusun.baron.player.api.MarriageService;
import ch.fusun.baron.player.api.PlayerService;
import ch.fusun.baron.printing.MessagingService;
import ch.fusun.baron.turn.TurnTask;

/**
 * Makes new children with a certain probability for each married player couple
 */
public class MakeChildrenTurnTask implements TurnTask {

	@Inject
	private transient MarriageService marriageService;
	@Inject
	private transient PlayerService playerService;
	@Inject
	private transient MessagingService messagingService;
	@Configure(value = "0.25")
	private double CHILDREN_PROBABILITY;
	@Configure(value = "16")
	private int AGE_FOR_CHILDREN;

	/**
	 * Injection constructor
	 */
	public MakeChildrenTurnTask() {

	}

	@Override
	public void execute() {
		for (Player player : playerService.getAllPlayers()) {
			if (Gender.FEMALE.equals(player.getGender())
					&& player.getAge() >= AGE_FOR_CHILDREN && !player.isDead()) {
				if (marriageService.isMarried(player)) {
					if (Math.random() < CHILDREN_PROBABILITY) {
						Player husband = marriageService.getSpouse(player);
						if (husband.getAge() >= AGE_FOR_CHILDREN
								&& !husband.isDead()) {
							Dynasty dynasty = playerService.getDynasty(husband);
							Gender gender = Gender.random();
							Player child = playerService
									.generateNewPlayer(gender);
							child.setFather(husband);
							child.setMother(player);
							child.setAge(0);
							playerService.addPlayerToDynasty(dynasty, child);
							messagingService
									.addMessage(
											null,
											"A new child was born for " + husband.getName() //$NON-NLS-1$
													+ " and " + player.getName() + ": " //$NON-NLS-1$ //$NON-NLS-2$
													+ child.getName() + " of " //$NON-NLS-1$
													+ dynasty.getName() + "."); //$NON-NLS-1$
						}
					}
				}
			}
		}
	}
}
